package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.List;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.Expert.reviewImages;
import com.flycent.hqhs.bean.PageEntity;
import com.flycent.hqhs.bean.ProductReviews;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.HorizontalListView;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy;
import com.flycent.hqhs.ui.view.RefreshViewLoadMoreProxy.OnLoadDataActionListener;
import com.flycent.hqhs.util.DateTimeUtil;
import com.flycent.hqhs.util.ImageUtil;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * @author fbl
 *   商品评价展示列表
 */
public class ProductEvaluationActivity extends BackableTitleBarActivity implements OnLoadDataActionListener{
	@ViewInject(id = R.id.product_ecaluation_empty_relat) RelativeLayout mEmptyRelat;


	PullToRefreshListView mRefreshListView;
	RefreshViewLoadMoreProxy mLoadMoreProxy;
	private ProductEvaluationAdapter mAdapter;
	private int nowpage = 1;
	private String  proId;
	private List<ProductReviews> mProductReviews;
	private ProductHorizonAdapter mHorAdapter;
	private Handler mHandler = new MyHandler(this);


	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_product_evaluation);
		FinalActivity.initInjectedView(this);
		getTitleBar().setTitle(R.string.title_product_evaluation);
		proId = getIntent().getStringExtra("proId");

		mRefreshListView = (PullToRefreshListView) findViewById(R.id.product_ecaluation_list);
		mRefreshListView.setEmptyView(mEmptyRelat);
		mRefreshListView.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));

		mAdapter = new ProductEvaluationAdapter(this,R.layout.item_product_evaluation);
		mRefreshListView.setAdapter(mAdapter);

		mLoadMoreProxy = new RefreshViewLoadMoreProxy(mRefreshListView, Mode.BOTH,0,0);
		mLoadMoreProxy.setOnLoadDataActionListener(this);
		mLoadMoreProxy.refreshing();

	}


	@Override
	public void onRefresh(int page) {
		updateMessageList(1, true);
	}
	@Override
	public void onLoadMore(int page) {
		nowpage++;
		updateMessageList(nowpage, false);
	}

	private void updateMessageList(final int pageNum,final boolean isRefresh){
		new Thread(){
			@SuppressLint("HandlerLeak") public void run() {
				try {
					PageEntity<ProductReviews> mEntity = WebClient.getInstance(ProductEvaluationActivity.this).getProductReviews(proId);
					mProductReviews = mEntity.getContent();
					if(pageNum > mEntity.getTotalPages()){
						App.showShortToast(R.string.the_end_page);
						mProductReviews = null;
					}

				} catch (WebException e) {
					if (WebException.TYPE_SERVER_RETURN_NULL.equals(e.getStatusCode()))
						mProductReviews = null;
					else{
						e.printStackTrace();
					}
				}catch (Exception e){
					App.showShortToast(R.string.unknownerror);
				}
				if(isRefresh)
					mHandler.sendEmptyMessage(0);
				else 
					mHandler.sendEmptyMessage(1);
			};
		}.start();

	}

	@SuppressLint("HandlerLeak")
	private class MyHandler extends Handler{

		private WeakReference<Activity> mActivity;

		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);

			if (mActivity.get() != null ) {
				switch (msg.what) {
				case 0:
					mAdapter.update(mProductReviews);
					mRefreshListView.onRefreshComplete();
					break;
				case 1:
					mAdapter.append(mProductReviews);
					mRefreshListView.onRefreshComplete();
					break;
				default:
					break;
				}
			}
		}
	}


	public class ProductEvaluationAdapter extends AbsViewHolderAdapter<ProductReviews>{

		public ProductEvaluationAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}
		@Override
		protected void bindData(int pos, ProductReviews itemData) {
			TextView mUserNameText = getViewFromHolder(R.id.product_evaluation_username);
			TextView mReviewTimeText = getViewFromHolder(R.id.product_evaluation_time);
			TextView mBuyTimeText = getViewFromHolder(R.id.product_evaluation_text_date);
			TextView mContentText = getViewFromHolder(R.id.product_evaluation_content_text);
			TextView mColorText = getViewFromHolder(R.id.product_evaluation_text_color);
			TextView mSizeText = getViewFromHolder(R.id.product_evaluation_text_model);
			LinearLayout mLin = getViewFromHolder(R.id.item_product_evaluation_double_lin);
			HorizontalListView mLists = getViewFromHolder(R.id.item_product_evaluation_list);

			mUserNameText.setText(itemData.getUsername());
			mContentText.setText(itemData.getContent());
			for (int i = 0; i < itemData.getItem().getSpecificationValues().size(); i++) {
				if(i == 0 )
					mColorText.setText(itemData.getItem().getSpecificationValues().get(0).getName());
				if( i == 1)
					mSizeText.setText(itemData.getItem().getSpecificationValues().get(1).getName());
			}
			mReviewTimeText.setText(DateTimeUtil.getDateTime1(itemData.getReviewDate()));
			mBuyTimeText.setText(DateTimeUtil.getDateTime1(itemData.getPurchaseDate()));

			if(itemData.getReviewImages() != null && itemData.getReviewImages().size() > 0 ){

				final String [] ss = new String[itemData.getReviewImages().size()]; 
				for (int i = 0; i < itemData.getReviewImages().size(); i++) {
					ss[i] = itemData.getReviewImages().get(i).getUrl();
				}

				mLin.setVisibility(View.VISIBLE);
				mHorAdapter = new ProductHorizonAdapter(ProductEvaluationActivity.this, R.layout.item_product_review_horizontal_list);
				mLists.setAdapter(mHorAdapter);
				mHorAdapter.update(itemData.getReviewImages());

				mLists.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						ImageUtil.imageBrower(ProductEvaluationActivity.this,position,ss);
					}

				});

			}else {
				mLin.setVisibility(View.GONE);
			}
		}
	}

	/** 多个商品下横向图片滑动 */
	public  class ProductHorizonAdapter extends AbsViewHolderAdapter<reviewImages>{
		public ProductHorizonAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, reviewImages itemData) {
			ImageView mImg = getViewFromHolder(R.id.item_product_review_img);
			ImageLoader.getInstance().displayImage(itemData.getUrl(), mImg);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	}

}
